using System.Collections.Generic;
using ArmyManager.Commands;
using ArmyManager.Items;
using ArmyManager.Units;
using ArmyManager.Utils;
using System.Linq;

namespace ArmyManager.Strategies
{
	public class ItemDistributionStrategy : IItemDistributionStrategy
	{
		private readonly ItemAttribute.AttributeTypes _attributeType;
		ItemHeap _items;

		public List<Item> RemainingItems { get { return _items.ItemsList; } }
		public bool IsFinished()
		{
			return _items.IsEmpty();
		}

		public ItemDistributionStrategy(ItemAttribute.AttributeTypes attributeType)
		{
			_attributeType = attributeType;
			_items = new ItemHeap(new Item[0], _attributeType);
		}

		public void Initialize(List<Item> items)
		{
			_items = new ItemHeap(items, _attributeType);
		}

		public ICommand Distribute(Unit unit)
		{
			CommandList commands = new CommandList();
			foreach (Item.ItemTypes itemType in _items.ItemTypes)
			{
				Item oldItem = unit.Items.FirstOrDefault(i => i.ItemType == itemType);
				if (oldItem == null || (GetAttributeAmount(oldItem) < GetAttributeAmount(_items.Peek(itemType))))
				{
					Item newItem = _items.Pop(itemType);
					ReplaceUnitItemCommand command = new ReplaceUnitItemCommand(unit, newItem);
					command.Execute();
					if (command.OldObject.CanKeep)
					{
						_items.Push(command.OldObject);
					}
					commands.Add(command);
				}
			}
			return commands;
		}

		private int GetAttributeAmount(Item item)
		{
			ItemAttribute attribute = item.Attributes.FirstOrDefault(a => a.AttributeType == _attributeType);
			return attribute != null ? attribute.Amount : 0;
		}
	}
}